package com.freewater.springboot.demo.dataaccess.transaction.listener;

import com.freewater.springboot.demo.dataaccess.transaction.listener.entity.Order;
import com.freewater.springboot.demo.dataaccess.transaction.listener.repository.OrderRepository;
import lombok.AllArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@AllArgsConstructor
public class OrderService {

    private OrderRepository orderRepository;
    private ApplicationEventPublisher eventPublisher;

    @Transactional
    public void createOrder(Order order) {
        // 创建订单
        this.orderRepository.save(order);
        // 发布事件
        this.eventPublisher.publishEvent(new OrderCreatedEvent(order.getId(), new Date()));
    }

    @Transactional
    public void createOrderWithError(Order order) {
        // 创建订单
        this.orderRepository.save(order);
        // 发布事件
        this.eventPublisher.publishEvent(new OrderCreatedEvent(order.getId(), new Date()));
        // 测试异常
        throw new RuntimeException("测试异常");
    }

    @Transactional
    public Order findOrderById(Long id) {
        // 查询订单
        return this.orderRepository.findById(id).orElse(null);
    }
}
